package com.hyper_yang.javase.multiThread.notify.lockBlock;

public class Base {
    public static void main(String[] args) throws InterruptedException {
        Bar bar = new Bar();

        Thread cook = new Thread(new CookRunnable(bar), "湘菜大厨");

        Thread waiter = new Thread(new WaiterRunnable(bar), "小二");

        cook.start();

        waiter.start();
    }
}

class Bar {
    // 记录菜品的数量
    int count;
}

class CookRunnable implements Runnable {
    Bar bar;

    public CookRunnable(Bar bar) {
        this.bar = bar;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (bar) {
                try {
                    if (bar.count >= 10) {
                        System.out.println("吧台满了，服务员快端菜");
                        bar.wait(); // 厨师等待服务员上菜，释放吧台锁
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                // 做菜
                bar.count++;
                System.out.println(Thread.currentThread().getName() + "做了一道菜，吧台上有" + bar.count + "道菜");

                // 通知服务员，吧台未空，可以上菜
                bar.notify();
            }
        }
    }
}

class WaiterRunnable implements Runnable {
    Bar bar;

    public WaiterRunnable(Bar bar) {
        this.bar = bar;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (bar) {
                try {
                    if (bar.count <= 0) {
                        System.out.println("吧台空了，厨师快做菜");
                        bar.wait(); // 服务员等待厨师做菜，释放吧台锁
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                // 端菜
                bar.count--;
                System.out.println(Thread.currentThread().getName() + "端走了一道菜，吧台剩余" + bar.count + "道菜");

                // 通知厨师，吧台未满，可以做菜
                bar.notify();
            }
        }
    }
}